package com.cats.bi.sqltool.basic;


import com.cats.bi.sqltool.SQLString;
import com.cats.bi.sqltool.syntax.Union;
import com.cats.bi.sqltool.syntax.sort.AbstractSort;

/**
 * @author wang
 */
public abstract class AbstractSearchable<T extends AbstractSearchable<T>> implements SQLString {
    private AbstractSort orderBy;
    private int limitOffset = -1;
    private int limit = 0;

    public void orderBy(AbstractSort orderBy) {
        this.orderBy = orderBy;
    }

    public T limit(int limit) {
        this.limit = limit;
        return (T) this;
    }

    public T limit(int offset, int limit) {
        this.limitOffset = offset;
        this.limit = limit;
        return (T) this;
    }

    /**
     * order by
     *
     * @param sql
     */
    protected void sort(StringBuilder sql) {
        if (orderBy != null) {
            orderBy.toSql(sql);
        }
    }

    /**
     * limit
     *
     * @param sql
     */
    protected void limit(StringBuilder sql) {
        if (limit > 0) {
            sql.append(" LIMIT ");
            if (limitOffset >= 0) {
                sql.append(limitOffset).append(',');
            }
            sql.append(limit);
        }
    }

    /**
     * 字符串 union
     *
     * @param select
     * @return
     */
    public abstract Union union(String select);

    /**
     * Select union
     *
     * @param select
     * @return
     */
    public abstract Union union(Select select);

    /**
     * select union all
     *
     * @param select
     * @return
     */
    public abstract Union unionAll(Select select);

    /**
     * String union all
     *
     * @param select
     * @return
     */
    public abstract Union unionAll(String select);
}